import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../class/notifier.dart';
import '../tool/tool.dart';

class LogView extends StatefulWidget {
  const LogView({super.key});

  @override
  State<LogView> createState() => _LogViewState();
}

///iOS风格的弹窗
Future<void> _openCupertinoDialog(BuildContext context) async {
  final bool clean = await showCupertinoDialog(
    context: context,
    barrierDismissible: true,
    builder: (BuildContext context) {
      return CupertinoAlertDialog(
        title: const Text('注意'),
        content: const Text('是否清除日志？'),
        actions: [
          CupertinoDialogAction(
            child: const Text('取消', style: TextStyle(color: Colors.black)),
            onPressed: () {
              Navigator.pop(context, false); // 关闭对话框
            },
          ),
          CupertinoDialogAction(
            child: const Text('清除', style: TextStyle(color: BLUE)),
            onPressed: () {
              Navigator.pop(context, true); // 关闭对话框
            },
          ),
        ],
      );
    },
  );
  if (clean == false) {
    return;
  }
  Provider.of<LogNotifier>(context, listen: false).clear();
}

class _LogViewState extends State<LogView> {
  @override
  Widget build(BuildContext context) {
    final logNotifier = Provider.of<LogNotifier>(context);

    return Drawer(
      backgroundColor: Colors.black,
      child: Column(
        children: [
          ListTile(
            title: const Text(
              'Log',
              textAlign: TextAlign.left,
              style: TextStyle(color: Colors.white),
            ),
            leading: InkWell(
                child: const Icon(
                  Icons.message,
                  color: Colors.redAccent,
                  size: 30,
                ),
                onTap: () {
                  _openCupertinoDialog(context);
                }),
          ),
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.only(left: 10),
              itemCount: logNotifier.logs.length,
              itemBuilder: (context, index) {
                String item = logNotifier.logs[index];
                bool isWrite = item.contains('写入') || item.contains('擦除');
                String end = isWrite ? '' : '------------------------------';

                return Text(
                  '$item\n$end',
                  style: const TextStyle(
                      color: Colors.green, backgroundColor: Colors.black),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
